from typing import List

from openai import OpenAI, AsyncOpenAI

from openai.types.beta.assistant import Assistant

from HomeAutoAI.common.utils.ThreadLocal import get_cur_user
from llm.entity.metadatas import AssistantMetadata
from llm.entity.vo.AssitantInfoVO import AssistantInfoVO
from llm.prompt.OneNetPrompts import OneNetPrompt, OneNetParserPrompt

from llm.models import Assistants, Threads
from llm.entity.dao.AssistantsDAO import AssistantsDAO
from users.models import Users
from dotenv import load_dotenv
import os

# 加载 .env 文件
load_dotenv(override=True)

client = OpenAI()


class AssistantService:

    @classmethod
    def create_for_parser(cls, user: Users, assistant_name: str,
                          metadata: AssistantMetadata = None) -> Assistant:
        """
        为用户创建智能家居助手（Assistant），并与用户的user_id绑定,并存储到数据库中,用于指令解析
        :param metadata:
        :param user:
        :param assistant_name:
        :return:
        """

        assistant: Assistant = client.beta.assistants.create(
            model="gpt-4o-mini",
            name=assistant_name,
            instructions=OneNetParserPrompt,  #TODO: 这里的prompt是写死的
            metadata=metadata,
            tools=[{"type": "file_search"}, {"type": "function"}]
        )
        # Assistants.objects.create(
        #     assistant_name=assistant.name,
        #     assistant_id=assistant.id,
        #     user_id_id=user_id
        # )
        AssistantsDAO.add(assistant, user=user)
        return assistant

    #TODO: 这个create还需要多完善。同时要要添加function-calling(可调用的方法,相当于添加配置文件）
    # 和file_search(文件搜索)的功能,目前测试先用写死了的
    @classmethod
    def create(cls, user_id: str, assistant_name: str, prompt: str) -> Assistant:
        """
        创建智能家居助手（Assistant）,并与用户的user_id绑定,并存储到数据库中,不限制提示词
        :param prompt:
        :param user_id:
        :param assistant_name:
        :return:
        """

    @classmethod
    def update(cls, assistant_id: str) -> Assistant:
        """
        更新智能家居助手（Assistant）,为其添加function-calling(可调用的方法）
        :param assistant_id:
        :return:
        """
        client = OpenAI()
        client.beta.assistants.update(
            tools=[
                {

                }
            ]
        )
        pass

    @classmethod
    def get_default(cls) -> Assistants:
        """
        获取当前用户默认的智能家居助手（数据库模型）
        :return:
        """
        for assistant in Assistants.objects.filter(get_cur_user()):
            pass

    @classmethod
    def get_all(cls, user: Users) -> List[AssistantInfoVO]:
        """
        获取当前用户的所有智能家居助手（数据库模型）
        :param user:
        :return:
        """
        try:
            vo_list = []
            assistant_list = AssistantsDAO.get_all(user)
            for assistant in assistant_list:
                vo = AssistantInfoVO(
                    assistant_id=assistant.assistant_id,
                    user_id=user.user_id,
                    assistant_name=assistant.assistant_name,
                    vector_id=assistant.attached_vector_store_id
                )
                vo_list.append(vo.dict())
            return vo_list
        except Exception as e:
            print(f"AssistantService.get_all error: {e}")
            raise e
